package com.zkh360.service.message.auth;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.zkh360.service.message.domain.SysRoles;
import com.zkh360.service.message.mapper.RoleMapper;
import com.zkh360.service.message.mapper.UsersMapper;

/**
 * 该类的主要作用是为Spring Security提供一个经过用户认证后的UserDetails。
 * 该UserDetails包括用户名、密码、是否可用、是否过期等信息。
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        //得到用户的权限
        List<SysRoles> roleList = roleMapper.getRolesByUser(null, username, 0, 10000);
        List<GrantedAuthority> authsList = new ArrayList<>();
        for (SysRoles role : roleList) {
            authsList.add(new SimpleGrantedAuthority(role.getRole_name()));
        }

        //取得用户的密码
        String password = usersMapper.getPasswordByUsername(username);
        return new org.springframework.security.core.userdetails.User(username, password, true, true, true, true, authsList);
    }
}